﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IUploading;
using System.Reflection;
using System.IO;
using LogLib;
using Newtonsoft.Json.Linq;
using ComLib.ComType;

namespace LocalFileCopying
{
    public class FileCopying : IUpload
    {
        private string _error = "";
        public string ErrorMessage
        {
            get
            {
                return _error;
            }
        }

        private string _appName = Assembly.GetExecutingAssembly().GetName().Name;
        public string InterfaceName
        {
            get
            {
                return _appName;
            }
        }

        public int TimeoutMillisecond
        {
            get;
            set;
        }

        public int ID
        {
            set;
            get;
        }

        public bool Inited
        {
            get;
            private set;
        }

        public bool Closed
        {
            get;
            private set;
        }

        private CopyingOption _option = new CopyingOption();

        /// <summary>
        /// 拷贝文件的最终目录
        /// </summary>
        private string _destCopyDirectory = "";

        private void LoadSettings()
        {
            if (!File.Exists(_option.ConfigFilePath))
            {
                _option.Save();
            }
            else
            {
                _option.Load();
            }
        }

        public FileCopying()
        {
            Inited = false;
            Closed = false;
            LoadSettings();
        }

        public FileCopying(CopyingOption opt)
        {
            Inited = false;
            Closed = false;
            _option = opt;
        }
        
        public bool Login(string inParam, out string outParam)
        {
            outParam = "";
            Log.AddBeginningBoundary();
            Inited = true;
            return true;
        }

        private void TryDeleteFile(string strFile)
        {
            try
            {
                if (File.Exists(strFile))
                {
                    File.Delete(strFile);
                }
            }
            catch (Exception ex)
            {
                Log.WriteAsync(ex.ToString());
            }
        }

        private bool CopyPhoto(string file, string photoName)
        {
            string extension = Path.GetExtension(file);
            string filename = photoName + extension;
            string destFile = Path.Combine(_destCopyDirectory, filename);
            try
            {
                File.Copy(file, destFile, true);
                string strLog = string.Format("文件{0}已经成功复制到{1}", file, destFile);
                Log.WriteAsync(strLog);
                return true;
            }
            catch (Exception ex)
            {
                _error = string.Format("文件{0}复制时发生了异常，\n异常详情:{1}", file, ex.Message);
                Log.WriteException(ex.ToString());
                Log.WriteAsync(_error);
                return false;
            }                  
        }

        public void Logout()
        {
            if (!Inited)
            {
                return;
            }
            Closed = true;
            Log.AddEndingBoundary();
        }

        public bool Test(string param, out string outParam)
        {
            outParam = "";
            return true;
        }

        public bool Query(string param, out string outParam)
        {
            outParam = "";
            return true;
        }

        public bool Post(string param, out string outParam)
        {
            _error = "";
            outParam = "";
            if (!CreatDestDirectory())
            {
                return false;
            }       
            JObject inParams = JObject.Parse(param);
            try
            {
                string photoName = (string)inParams["PhotoName"];
                string origPhotoPath = (string)inParams["OrigPhotoPath"];
                string destPhotoPath = (string)inParams["DestPhotoPath"];                            
                switch (_option.CopyOption)
                {
                    case CopyOptions.Both:
                        return CopyPhoto(origPhotoPath, photoName)
                            && CopyPhoto(destPhotoPath, photoName);                
                    case CopyOptions.Orginal:
                        return CopyPhoto(origPhotoPath, photoName);
                    case CopyOptions.Outcome:
                        return CopyPhoto(destPhotoPath, photoName);
                    default:
                        return true;
                }
            }
            catch (Exception ex)
            {
                _error = "复制文件发生了异常, 异常详情: " + ex.Message;
                Log.WriteAsync(_error);
                Log.WriteException(ex.ToString());
                return false;
            }    
        }

        public void ShowConfigDialog(string inParam)
        {
            FormCopyingOption form = new FormCopyingOption();
            if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                _option = form.Option;
            }
        }

        /// <summary>
        /// 创建拷贝路径
        /// </summary>
        /// <returns></returns>
        private string CreatCopyPathString()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(_option.DestDirectory);
            if (!_option.DestDirectory.EndsWith("\\") || !_option.DestDirectory.EndsWith("/"))
            {              
                builder.Append("\\");
            }
            switch (_option.DirFormat)
            {
                case DirectoryFormat.EveryDay:
                    builder.Append(System.DateTime.Now.ToString("yyyyMMdd"));
                    builder.Append("\\");
                    break;
                case DirectoryFormat.EveryMonth:
                    builder.Append(System.DateTime.Now.ToString("yyyyMM"));
                    builder.Append("\\");
                    builder.Append(System.DateTime.Now.ToString("dd"));
                    builder.Append("\\");
                    break;
                case DirectoryFormat.None:
                    break;
                default:
                    break;
            }
            return builder.ToString();
        }
       
        public bool CreatDestDirectory()
        {
            _destCopyDirectory = CreatCopyPathString();
            if (Directory.Exists(_destCopyDirectory))
            {
                return true;
            }
            _error = "";
            try
            {
                Directory.CreateDirectory(_destCopyDirectory);
                string strLog = string.Format("创建目录{0}成功!", _destCopyDirectory);
                Log.WriteAsync(strLog);
                return true;
            }
            catch (Exception ex)
            {
                _error = string.Format("创建目录{0}失败! \n异常详情:{1}",
                   _destCopyDirectory, ex.Message);
                Log.WriteException(ex.ToString());
                Log.WriteAsync(_error);
                return false;
            }
        }
    }
}
